package com.example.boos;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.bumptech.glide.Glide;
import com.example.boos.HttpUtil.MyPost;
import com.example.boos.context.BossInfo;
import com.example.boos.pojo.Boss;
import com.example.boos.pojo.Food;
import com.example.boos.pojo.FoodType;
import com.example.boos.pojo.Orders;
import com.example.boos.pojo.Store;
import com.example.boos.service.RabbitService;
import com.example.boos.stores.stores_activity;
import com.example.boos.ui.home.HomeFragment;
import com.example.boos.ui.home.RightAdapter;
import com.example.boos.ui.notifications.NotificationsFragment;
import com.example.boos.util.MyThreadPool;
import com.example.boos.util.RequestPermissionUtil;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    public static Handler handler = new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 1:
                    HomeFragment.updateLeftALL(HomeFragment.leftData);
                    HomeFragment.updateRightAll(HomeFragment.rightData);
                    title.setText(BossInfo.currentStore.getStoreName());
                    Glide.with(MainActivity.getMainActivity()).load(BossInfo.currentStore.getStoreImage()).into(bg);
                    mSubTitle.setText(BossInfo.currentStore.getStoreName());
                    break;
                case 2:
                    HomeFragment.updateLeft();
                    break;
                case 3:
                    if((Boolean)msg.obj){
                        HomeFragment.updateRight();
                        Toast.makeText(MainActivity.getMainActivity(),"删除成功！",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(MainActivity.getMainActivity(),"删除失败，请重试！",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 4:
                    if((Boolean) msg.obj){
                        // 更新成功
                        HomeFragment.updateRight();
                        Toast.makeText(MainActivity.getMainActivity(),"更新成功！",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(MainActivity.getMainActivity(),"更新失败，请重试！",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 5:
                    // 更新店铺图片
                    if(!"".equals(msg.obj)){
                        HomeFragment.updateStoreImage((String) msg.obj);
                        // 更新一下店铺数据
                        BossInfo.currentStore.setStoreImage((String) msg.obj);
                    }
                    break;
                case 6:
                    // 更新菜品图片
                    if(!"".equals(msg.obj)){
                        HomeFragment.updateFoodImage((String) msg.obj);
                    }
                    break;
                case 7:
                    if((Boolean)msg.obj){
                        // 添加菜品成功，通知刷新
                        HomeFragment.updateRight();
                        Toast.makeText(MainActivity.getMainActivity(),"添加成功！",Toast.LENGTH_SHORT).show();
                    }else{
                        // 添加失败
                        Toast.makeText(MainActivity.getMainActivity(),"添加失败，请重试！",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 8:
                    Toast.makeText(getMainActivity(),"你有一笔新的订单！",Toast.LENGTH_LONG).show();
                    if(NotificationsFragment.data != null){
                        NotificationsFragment.data.add(0, (Orders) msg.obj);
                    }
                    break;
                case 9:
                    // 更新店铺信息那里的店铺图片
                    Toast.makeText(getMainActivity(),"店铺图片更新完成！",Toast.LENGTH_SHORT).show();
                    Glide.with(getMainActivity()).load(BossInfo.currentStore.getStoreImage()).into((ImageView) msg.obj);
                    break;
                case 10:
                    Orders orders = (Orders) msg.obj;
                    Toast.makeText(getMainActivity(),"订单:"+orders.getId()+"被取消！",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private static ImageView bg;
    private static TextView title;
    static TextView mSubTitle;

    public static Boolean isStoreIamge = false;

    private static Activity activity;

    public MainActivity(){
        activity = this;
    }

    public static Activity getMainActivity(){
        return activity;
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK ) {
            // 如果是 相册返回的话
            if (requestCode == 1 && null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                //获取到图片的本地地址
                final String picturePath = cursor.getString(columnIndex);
                // 上传图片 先显示 ，再上传会比较好吧。
                //upload(picturePath);
                // 通知更新呗
                //Glide.with(this).load(picturePath).into(img);
                // 上传图片
                if(!isStoreIamge){
                    // 菜品图片上传
                    MyThreadPool.doJob(new Runnable() {
                        @Override
                        public void run() {
                            String url = "updateFoodImage";
                            Integer id = HomeFragment.rightData.get(RightAdapter.position).getId();
                            String imageUrl = (String) MyPost.uploadImage(url,picturePath,String.valueOf(id));
                            Message msg = new Message();
                            msg.obj = imageUrl;
                            msg.what = 6;
                            handler.sendMessage(msg);
                        }
                    });
                }else{
                    // 店铺图片上传
                    MyThreadPool.doJob(new Runnable() {
                        @Override
                        public void run() {
                            String url = (String) MyPost.uploadImage("updateStoreImage",picturePath, String.valueOf(BossInfo.currentStoreId));
                            Message msg =new Message();
                            msg.obj = url;
                            msg.what =5;
                            handler.sendMessage(msg);
                        }
                    });
                    isStoreIamge = false;
                }
                cursor.close();
            }
            else if(requestCode == 2 && null != data){
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                //获取到图片的本地地址
                final String picturePath = cursor.getString(columnIndex);
                // 显示图片
                ImageView image = HomeFragment.popView.findViewById(R.id.addFoodImage);
                TextView imageSrc = HomeFragment.popView.findViewById(R.id.foodImageSrc);
                imageSrc.setText(picturePath);
                Glide.with(this).load(picturePath).into(image);
                cursor.close();
            }else if(requestCode == 3 && data != null){
                // 修改店铺的图片
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                //获取到图片的本地地址
                final String picturePath = cursor.getString(columnIndex);
                ImageView imageView = findViewById(R.id.update_storeImage);
                // 更新一下图片
                // 上传图片
                MyThreadPool.doJob(new Runnable() {
                    @Override
                    public void run() {

                        String url = "updateStoreImage";
                        String imageUrl = (String) MyPost.uploadImage(url,picturePath,String.valueOf(BossInfo.currentStoreId));
                        if(imageUrl!=null && !"".equals(imageUrl)){
                            Message msg = new Message();
                            msg.obj = imageView;
                            BossInfo.currentStore.setStoreImage(imageUrl);
                            // 通知更新
                            msg.what = 9;
                            handler.sendMessage(msg);
                        }

                    }
                });

            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplication());
        setContentView(R.layout.activity_main);
        RequestPermissionUtil.requestPermission(this);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications,R.id.endOrder,R.id.myStoreInfo)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
        initData();
        // 创建一个消息队列监听服务
        Intent intent = new Intent(MainActivity.this, RabbitService.class);
        MainActivity.this.startService(intent);
    }

    // 加个菜单吧 （返回键）
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.back_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_back:
                // 返回到店铺选择页面
                HomeFragment.view = null;
                Intent intent = new Intent();
                Intent intent1 = new Intent(this,RabbitService.class);
                stopService(intent1);   // 关闭一下服务
                intent.setComponent(new ComponentName(this, stores_activity.class));
                startActivity(intent);
                // 要把 HomeFragment的 view 置于空
                NotificationsFragment.data = null;

                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStart() {
        super.onStart();
        bg = findViewById(R.id.bg);
        title = findViewById(R.id.title);
        mSubTitle = (TextView) findViewById(R.id.subtitle);
    }

    private void initData(){
        MyThreadPool.doJob(new Runnable() {
            @Override
            public void run() {
                // 获取到当前店铺的 food 和 foodType 以及 StoreName
                HomeFragment.leftData = (List<FoodType>) MyPost.doPost("loadStoreHome", BossInfo.currentStoreId);
                HomeFragment.rightData = (List<Food>)MyPost.doPost("getFoods", BossInfo.currentStoreId);
                BossInfo.currentStore = (Store) MyPost.doPost("getStoreInfo", BossInfo.currentStoreId);
                Message msg = new Message();
                msg.what  = 1;
                handler.sendMessage(msg);
            }
        });

    }

}